from Common.BaseModel import db, BaseModel
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from flask_login import UserMixin


class AccountModel(BaseModel, UserMixin):
    __tablename__ = 'sys_account'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # emp_id = db.Column(db.Integer, db.ForeignKey('hr_employee.id', ondelete='RESTRICT', onupdate='CASCADE'))
    username = db.Column(db.String(64), unique=True, nullable=False)
    _password = db.Column(db.String(128), nullable=False)
    status = db.Column(db.Boolean, default=True)
    create_time = db.Column(db.DateTime)
    login_time = db.Column(db.DateTime)
    login_ip = db.Column(db.String(32))

    def __init__(self, dataDict):
        if not isinstance(dataDict, dict):
            return
        self.username = dataDict['username']
        self.password = dataDict['password']
        self.create_time = datetime.now()

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    def check_password(self, value):
        return check_password_hash(self.password, value)


class RoleModel(BaseModel):
    __tablename__ = 'sys_role'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(64), unique=True)
    desc = db.Column(db.Text)

    # 拥有的帐号
    accounts = db.relationship('AccountModel', secondary='sys_role_account', backref='roles')
    # 拥有的操作
    actions = db.relationship('ActionModel', secondary='sys_role_action', backref='roles', lazy='dynamic')

    def __init__(self, dataDict):
        if not isinstance(dataDict, dict):
            return
        self.name = dataDict['name']
        self.desc = dataDict['desc']


class RoleAccount(BaseModel):
    __tablename__ = 'sys_role_account'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    account_id = db.Column(db.Integer, db.ForeignKey('sys_account.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer, db.ForeignKey('sys_role.id', ondelete='CASCADE'))


class RoleAction(BaseModel):
    __tablename__ = 'sys_role_action'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    action_id = db.Column(db.Integer, db.ForeignKey('sys_action.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer, db.ForeignKey('sys_role.id', ondelete='CASCADE'))
